<script lang="ts">
  import { onMount } from 'svelte';
  import { jumpBy2804, errorReport, matchStrchangeHTML } from './utils';
  import {
    getAuthApi,
    getShowApi,
    getHasAuthContentApi,
    getNoAuthContentApi,
    noAuthParams,
    getJumpContentApi
  } from './api';
  import { companyJudgeGood, companyJudgeBad, suggestion } from './options';

  import Empty from './Empty.svelte';

  import {
    type StatIds,
    type ListItem,
    type UserInfo,
    LandingType
  } from '../types/operateAdvanced.d.js';

  import moreImg from '../assets/more.png';
  import clickViewImg from '../assets/click-view.png';
  import type { ContentRes } from '@/types/api';

  // 整个组件是否展示
  let isShow: boolean = false;
  // 是否有权限
  let hasAuth: boolean = false;
  // 最终展示的风险提示列表
  let showBadList: ListItem[] = [];
  // 最终展示的投资亮点列表
  let showGoodList: ListItem[] = [];
  // 最终展示的操作建议列表
  let showSuggestionList: ListItem[] = [];
  // 更多内容
  const rightOptions = {
    right_content: '更多',
    right_link: ''
  };
  // 点击查看内容
  const suggestOptions = {
    suggest_content: '点击查看',
    suggest_link: ''
  };
  // 功能页地址
  const funcPage: string = `${window.location.protocol}//vaserviece.10jqka.com.cn/diagnosestock/index.html#/detail`;
  // 埋点信息
  export let statIds: StatIds = {
    show: '',
    more: '',
    clickView: ''
  };
  // 外部传入股票代码，股票名称，市场
  export let stockCode: string = '';
  export let stockName: string = '';
  export let market: string = '';
  export let userInfo: UserInfo = {
    userid: '',
    platform: '',
    versionid: ''
  };
  onMount(() => {
    new Promise((resolve, reject) => {
      getShowApi({}).then((res) => {
        isShow = res.data;
        isShow ? resolve(true) : reject(false);
      });
    })
      .then(getAuth)
      .then(getContent)
      .catch((error: Error | false) => {
        console.log(error);

        // 是错误才上报
        if (error) {
          errorReport({
            name: `引流高级诊股消费接口报错 ${error.name}`,
            message: error.message,
            stack: error.stack
          });
        }
      });
    // 其次判断是否有高级诊股
  });

  // 点击更多
  const clickMore = () => {
    window.hxmClickStat(statIds.more);
    if (hasAuth) {
      const url = `${funcPage}/${stockCode}/${market}/${stockName}`;
      if (stockCode && market && stockName) {
        jumpBy2804(url);
      } else {
        // todo 需要封装一个toast组件
        // alert('参数错误')
        errorReport({
          name: '跳转功能页错误',
          message: '方法名称clickMore',
          stack: `具体跳转参数${url}`
        });
      }
    } else {
      jumpLanding(false, LandingType.Right);
    }
  };
  // 跳转落地页
  const jumpLanding = (isClickView: boolean = false, type: LandingType) => {
    if (isClickView) {
      window.hxmClickStat(statIds.clickView);
    }
    const landingUrl =
      type === LandingType.Right ? rightOptions.right_link : suggestOptions.suggest_link;
    jumpBy2804(landingUrl);
  };
  // 获取当前用户是否有权限
  const getAuth = () => {
    window.hxmPageStat(statIds.show);
    return getAuthApi({ func_list: 'thssjzggn' }).then((res) => {
      hasAuth = res.data.thssjzggn;
    });
  };
  // 根据权限分别调用不同的接口
  const getMainContent = () => {
    const getContentFn: () => Promise<ContentRes> = hasAuth
      ? getHasAuthContentApi.bind(this, { stockCode })
      : getNoAuthContentApi.bind(this, {
          url: `${noAuthParams}?stockCode=${stockCode}`,
          config_key: 'advanceddiagnosis'
        });
    return getContentFn().then((res) => {
      const {
        suggestion: { suggestionList },
        synthesis: {
          companyJudgeGood: { goodList },
          companyJudgeBad: { badList }
        }
      } = res.data;
      showGoodList = goodList.map((item) => ({
        name: companyJudgeGood[item.key] || '',
        value: matchStrchangeHTML(item.value, 'good')
      }));
      showBadList = badList.map((item) => ({
        name: companyJudgeBad[item.key] || '',
        value: matchStrchangeHTML(item.value, 'bad')
      }));
      showSuggestionList = suggestionList.map((item) => {
        if (item.key === 'targetPrice') {
          const value = +item.value;
          return {
            name: suggestion[item.key] || '',
            value:
              value > 0
                ? `机构平均目标价<span class="red">${value.toFixed(2)}</span>`
                : '暂无机构目标价'
          };
        } else {
          return {
            name: suggestion[item.key] || '',
            value: matchStrchangeHTML(item.value, 'suggest')
          };
        }
      });
    });
  };
  // 获取权限位内容
  const getJumpContent = () =>
    getJumpContentApi({
      appid: '2',
      adtype: 'sjthsrbrgjx',
      width: '1080',
      height: '1920',
      ...userInfo
    }).then((res) => {
      const { suggest_content, suggest_link, right_content, right_link } = res.data.sjthsrbrgjx[0];
      suggestOptions.suggest_content = suggest_content;
      suggestOptions.suggest_link = suggest_link.url;
      rightOptions.right_content = right_content;
      rightOptions.right_link = right_link.url;
    });
  const getContent = () => Promise.all([getMainContent(), getJumpContent()]);
</script>

{#if isShow}
  <div class="operate-advanced">
    <div class="option">
      <div class="title">
        <span>投资亮点</span>
        <!-- svelte-ignore a11y-click-events-have-key-events -->
        <div class="more" on:click={clickMore}>
          <span>{rightOptions.right_content}</span><img src={moreImg} alt="" />
        </div>
      </div>
      <div class="contents tzld">
        {#if showGoodList.length}
          {#each showGoodList as { name, value }}
            <div class="tips">
              <div class="tips-title"><span>{name}</span></div>
              <div class="tips-content">
                {@html value}
              </div>
            </div>
          {/each}
        {:else}
          <Empty message="暂无投资亮点" />
        {/if}
      </div>
    </div>
    <div class="option">
      <div class="title">
        <span>风险提示</span>
      </div>
      <div class="contents fxts">
        {#if showBadList.length}
          {#each showBadList as { name, value }}
            <div class="tips">
              <div class="tips-title"><span>{name}</span></div>
              <div class="tips-content">
                {@html value}
              </div>
            </div>
          {/each}
        {:else}
          <Empty message="未发现潜在风险" />
        {/if}
      </div>
    </div>
    <div class="option">
      <div class="title">
        <div class="suggestion">
          操作建议{#if !hasAuth}
            <!-- svelte-ignore a11y-click-events-have-key-events -->
            <span class="click-view" on:click={jumpLanding.bind(this, true, LandingType.Suggest)}
              >{suggestOptions.suggest_content}<img src={clickViewImg} alt="" /></span
            >
          {/if}
        </div>
      </div>
      {#if hasAuth}
        <div class="contents czjy">
          {#if showSuggestionList.length}
            {#each showSuggestionList as { name, value }}
              <div class="tips">
                <div class="tips-title">{name}</div>
                <div class="tips-content">{@html value}</div>
              </div>
            {/each}
          {:else}
            <Empty message="暂无操作建议" />
          {/if}
        </div>
      {/if}
    </div>
  </div>
{/if}

<style lang="less">
  .operate-advanced {
    width: 100%;
    background: #ffffff;
    border-radius: 6px;
    box-sizing: border-box;
    // padding: 12px 10px 16px;
    :global(.red) {
      color: #fa3b32;
    }
    :global(.green) {
      color: #00b650;
    }
    .option {
      .title {
        display: flex;
        justify-content: space-between;
        font-family: PingFangSC-Medium;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.84);
        letter-spacing: 0;
        line-height: 18px;
        font-weight: bold;
        .suggestion {
          display: flex;
          align-items: center;
          .click-view {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-left: 4px;
            font-family: PingFangSC-Medium;
            font-size: 12px;
            color: #3366ff;
            letter-spacing: 0;
            text-align: right;
            line-height: 16px;
            font-weight: 500;
            img {
              width: 12px;
              height: 12px;
              margin-left: 2px;
            }
          }
        }
        .more {
          display: flex;
          align-items: center;
          span {
            font-family: PingFangSC-Regular;
            font-size: 12px;
            color: rgba(0, 0, 0, 0.32);
            letter-spacing: 0;
            text-align: right;
            line-height: 16px;
            font-weight: 400;
          }
          img {
            width: 12px;
            height: 12px;
            margin-left: 2px;
          }
        }
      }
      .contents {
        margin-top: 12px;
        margin-bottom: 16px;
        .tips {
          display: flex;
          margin-bottom: 8px;
          .red {
            color: #ff2436;
          }
          &-title {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-shrink: 0;
            width: 48px;
            height: 21px;
            span {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 48px;
              height: 16px;
              font-family: PingFangSC-Medium;
              font-size: 10px;
              letter-spacing: 0;
              text-align: right;
              line-height: 12px;
              font-weight: bold;
              border-radius: 4px;
            }
          }
          &-content {
            font-family: PingFangSC-Regular;
            font-size: 14px;
            color: rgba(0, 0, 0, 0.84);
            letter-spacing: 0;
            line-height: 21px;
            font-weight: 400;
            margin-left: 12px;
          }
        }
        &.tzld {
          .tips-title {
            span {
              background: rgba(254, 149, 0, 0.05);
              color: #fe9500;
            }
          }
        }
        &.fxts {
          .tips-title {
            span {
              background: rgba(51, 102, 255, 0.05);
              color: #3366ff;
            }
          }
        }
        &.czjy {
          .tips-title {
            font-family: PingFangSC-Regular;
            font-size: 14px;
            justify-content: start;
            color: rgba(0, 0, 0, 0.84);
            letter-spacing: 0;
            line-height: 21px;
            font-weight: 400;
            border-radius: 0;
          }
        }
      }
    }
  }
</style>
